import React from 'react';
import { Table ,Input,Button,Icon} from 'antd';
import {browserHistory,Link} from "react-router";
import reqwest from 'reqwest';
import "./examination.css"
import CommonTree from "../common/tree.js"
const Search = Input.Search;

let currPage=1; //保存当前页
let orderby ={field:'createDate',order:'descend' }; //记录排序列和排序的规则
let examId = null;
const columns = [{
    title: '试卷名称',
    dataIndex: 'examinationName',
    key:"examinationName",
},{
    title: '试卷总分',
    dataIndex: 'totalScore',
    key:"totalScore",
},{
    title: '及格分数',
    dataIndex: 'passScore',
    key:"passScore",
    sorter: true,
},{
    title: '题目总数',
    dataIndex: 'examNum',
    key:"examNum",
},{
    title: '更新时间',
    dataIndex: 'updateDate',
    key:"updateDate",
    sorter: true,
},{
    title: '创建时间',
    dataIndex: 'createDate',
    key:"createDate",
    sorter: true,
    /*
     render: name => `${name.first} ${name.last}`,
     */
    width: '20%',
}, {
    title: '创建人',
    dataIndex: 'creater',
    key:"creater",
    /* 筛选功能
     filters: [
     { text: 'Male', value: 'male' },
     { text: 'Female', value: 'female' },
     ],
     */
    width: '20%',
}];
class Examination extends React.Component {
     constructor(){
        super();
        this.state= {
            data: [],
            pagination: {},
            loading: false,
            selectedRowKeys: [], 
        };
    }
   
    onSelectChange(selectedRowKeys){
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        examId = selectedRowKeys;
        if(selectedRowKeys){
            console.log("画勾被执行了")
        }
        this.setState({ selectedRowKeys });
    };
    //搜索功能
    oSeach(value){
        this.fetch({
            orderBy:orderby.order === undefined ? undefined:orderby.order==="descend"?orderby.field+' desc':orderby.field+' asc',//把排序规则定义一下
            searchCondition:value //搜索参数
        });
        //undefined ? undefined:sorter.order==="descend"?sorter.field+' desc':sorter.field+' asc';
    };
    //表格排序，筛选，分页
    handleTableChange(pagination, filters, sorter){
        orderby.field = sorter.field; //排序的列
        orderby.order = sorter.order; //排序的规则
        const pager = this.state.pagination;  /*分页对象*/
        pager.current = pagination.current;/*分页当前页*/
        currPage=pagination.current;/*保存当前页*/
        this.setState({
            pagination: pager,/*设置分页*/
        });
        this.fetch({
            /*          sortField: sorter.field,
             sortOrder: sorter.order,*/
            pageNo: pagination.current, /*参数传给后台 当前页*/
            orderBy:sorter.order === undefined ? undefined:sorter.order==="descend"?sorter.field+' desc':sorter.field+' asc',/*改变升序降序单词（去除end）*/
            filters,
        });
    };
    /*异步请求  携带params（参数）*/
    fetch(params){
        console.log('params:', params);
        this.setState({ loading: true });
        reqwest({
            url: "http://192.168.2.9:8080/learn/s/resources/hExamination/",/*服务器地址*/
            //url: "http://192.168.2.176:8080/s/resources/hExamination/",/*联调地址（殷龙）*/
            method: 'post',
            data:params,
            type: 'json',
        }).then((data) => {
            examId=null;
            const pagination = this.state.pagination;/*本地分页对象*/
            pagination.pageSize = data.data.pageSize;/*设置一页多少数据*/
            // Read total count from server
            // pagination.total = data.totalCount;
            pagination.total = data.data.count;/*设置总数据数量*/
            let list = data.data.list;
            for(let i = 0; i < list.length; i++) {
                list[i]["key"]= Number(list[i].id);
            }
            this.setState({
                loading: false,
                data: list,/*后台表格数据*/
                pagination,
                selectedRowKeys: [],
            });
        });
    };
    componentDidMount() {
        this.fetch();
    };
    /*编辑功能*/
    editClick(){
        if(examId){
            if(examId.length == 1){
                browserHistory.push('/examination/edit/'+examId);
                examId = null;
            }else {
                alert("请选择一道题目")
            }
        }else {
            alert("请选择一道题目")
        }
    };
    /*删除功能*/
    delClick(){
        if (examId!=null&&examId.length>0){
            console.log(examId);
            this.delBtn({
                ids:examId.join(",")
            });
        }else {
            alert("请至少选择一道题目")
        }

    };
    delBtn(params){
        console.log('params:', params);
        reqwest({
            url: "http://192.168.2.9:8080/learn/s/resources/hExamination/delete",/*服务器地址*/
            //url: "http://192.168.2.176:8080/s/resources/hExamination/delete",/*联调地址（殷龙）*/
            method: 'post',
            data: params,
            type: 'json',
        }).then((data) => {
            this.fetch();
        });
    };

    render() {
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange.bind(this),
        };
        return (
            <div>
                <div className="N_myTree">
                    <CommonTree corpId="1" resourceType="1"> </CommonTree>
                </div>
                <div className="N_smallContent">
                    <div className="N_handleBox">
                        <Search
                            placeholder="请输入关键字"
                            style={{ width: 200 }}
                            onSearch={this.oSeach.bind(this)}
                            id="seachInput"
                        />
                        <div className="btnBox">
                            <Button size="small" onClick={()=>{browserHistory.push('/examination/add')}}><Icon type="plus" />新增</Button>
                            <Button size="small" onClick={this.editClick.bind(this)}><Icon type="edit" />编辑</Button>
                            <Button size="small"><Icon type="copy" />复制</Button>
                            <Button size="small"><Icon type="export" />移动</Button>
                            <Button size="small" onClick={this.delClick.bind(this)}><Icon type="delete" />删除</Button>
                        </div>
                    </div>
                    <Table columns={columns}
                                 rowSelection={rowSelection}
                                 dataSource={this.state.data} //降调取的数据转化成表格，自带属性方法
                                 pagination={this.state.pagination}//分页自带属性方法
                                 loading={this.state.loading}
                                 onChange={this.handleTableChange.bind(this)}
                    />
                </div>
            </div>
        );
    }
}
export default Examination